package cn.edu.cug.cs.gtl.plugins.catalog.tree;

import cn.edu.cug.cs.gtl.apis.ui.AbstractApplication;
import cn.edu.cug.cs.gtl.apis.ui.actions.AbstractAction;
import cn.edu.cug.cs.gtl.apis.ui.catalogtree.CatalogTree;
import cn.edu.cug.cs.gtl.apis.ui.tree.TreeNodeData;
import cn.edu.cug.cs.gtl.protos.DataCatalog;
import cn.edu.cug.cs.gtl.utils.postgresql.DataCatalogManager4Postgresql;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import java.awt.event.ActionEvent;
import java.util.Locale;
import java.util.ResourceBundle;

public class DeleteSelectCatalogAction extends AbstractAction {
    @Override
    public void initialize(AbstractApplication theApp) {
        this.theApp = theApp;
        ResourceBundle resourceBundle = ResourceBundle.getBundle("catalog-resource", Locale.getDefault());

        name = resourceBundle.getString("popupmenu.catalog.tree.delete_select_catalog");
        menuItem.setText(name);
        menuItem.addActionListener(this);
        ((CatalogTree) (theApp.getMainFrame().getCatalogPanel().getTreeComponent())).getCatalogNodePopupMenu().add(menuItem);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        CatalogTree tree = (CatalogTree) theApp.getMainFrame().getCatalogPanel().getTreeComponent();
        DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (selectNode == null || selectNode.getParent() == null) {
            JOptionPane.showMessageDialog(null, "未选中节点或选中节点为根节点", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        //在数据库中删除对应节点
        DataCatalog parentCatalog = (DataCatalog) ((TreeNodeData) (((DefaultMutableTreeNode) (selectNode.getParent())).getUserObject())).getRefObject();
        DataCatalog childCatalog = (DataCatalog) (((TreeNodeData) (selectNode.getUserObject())).getRefObject());
        DataCatalog ret = new DataCatalogManager4Postgresql().removeCatalog(parentCatalog.getName(), childCatalog.getName());
        if (ret == null) {
            JOptionPane.showMessageDialog(null, "删除失败", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        //移除一个节点并通知树的视图
        DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel();
        treeModel.removeNodeFromParent(selectNode);
    }
}
